<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '修改') + '能耗终端'"
    width="1000px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <tdMap
      :isShowCreateDialog.sync="mapShow"
      :data="latlng"
      @close="close"
      @result="getLatlng"
    >
    </tdMap>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>
<script>
import { maxCode, add, detail, edit } from "@/api/iot/network";
import {
  getParkList,
  getBuildingList,
  getFloorList,
  getArchitectureRoomList,
} from "@/api/basicdata/construction";
import { replaceDigit, dealElectricity } from "@/utils/index";
import tdMap from "@/views/resource/network/components/map";
import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import RemoteSelect from "@/components/Select/RemoteSelect";

export default {
  components: { FormButton, tdMap, CascaderSelect, RemoteSelect },
  props: {
    id: { type: [Number, String], default: "" },
    visible: { type: Boolean, default: false },
  },
  dicts: [
    "energy_subarea_type",
    "energy_subarea_child_type",
    "site_functions",
    "orientation",
  ],
  data() {
    return {
      parkOptions: [],
      buildingOptions: [],
      floorOptions: [],
      roomOptions: [],
      latlng: {
        lat: null,
        lng: null,
      },
      mapShow: false,
      loading: false,
      apsForm: {
        formRef: "form",
        formData: {
          sort: 99, // 设置默认值
          status: true,
          custom: false, // 保持和registerForm一致
        },
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 2,
              middle: true,
            },
            rules: {
              code: [
                {
                  required: true,
                  message: "请输入能耗终端编码",
                  trigger: "blur",
                },
                // { validator: this.validCode },
              ],
              name: [
                {
                  required: true,
                  message: "请输入能耗终端名称",
                  trigger: "blur",
                },
              ],
              latitude: [
                {
                  required: true,
                  message: "请输入或选择能耗终端经度",
                  trigger: ["blur", "change"],
                },
              ],
              longitude: [
                {
                  required: true,
                  message: "请输入或选择能耗终端纬度",
                  trigger: ["blur", "change"],
                },
              ],
              specialEnergyFlag: [
                {
                  required: true,
                  message: "请选择场所职能",
                  trigger: "change",
                },
              ],
              location: [
                {
                  required: true,
                  message: "请输入能耗终端地址",
                  trigger: "blur",
                },
              ],
              smartDeviceNum: [
                {
                  required: true,
                  message: "请输入智能设备数量",
                  trigger: "change",
                },
              ],
              // userNum: [
              //   {
              //     required: true,
              //     message: "请选择或输入用能人数",
              //     trigger: ["blur", "change"],
              //   },
              // ],
              orientation: [
                {
                  required: true,
                  message: "请选择朝向",
                  trigger: ["blur", "change"],
                },
              ],
              parkId: [
                {
                  required: true,
                  message: "请选择园区",
                  trigger: ["blur", "change"],
                },
              ],
              buildingId: [
                {
                  required: true,
                  message: "请选择楼幢",
                  trigger: ["blur", "change"],
                },
              ],
              floor: [
                {
                  required: true,
                  message: "请选择楼层",
                  trigger: ["blur", "change"],
                },
              ],
              architectureRoomIds: [
                {
                  required: true,
                  message: "请选择房间",
                  trigger: ["blur", "change"],
                },
              ],
              area: [
                { required: true, message: "请输入用能面积", trigger: "blur" },
              ],
              energySubarea: [
                {
                  required: true,
                  message: "请选择分区类别",
                  trigger: ["blur", "change"],
                },
              ],
              energySubareaChild: [
                {
                  required: true,
                  message: "请选择分区子类",
                  trigger: ["blur", "change"],
                },
              ],
            },
          },
          properties: {
            parkId: {
              typeName: "el-select",
              label: "园区",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$refs?.form?.setFieldValue("buildingId", "");
                          that.$refs?.form?.setFieldValue("floor", "");
                          that.$refs?.form?.setFieldValue(
                            "architectureRoomIds",
                            ""
                          );
                          that.getBuilding(value);
                        },
                      },
                    },
                    [
                      that.parkOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              typeName: "el-select",
              label: "楼幢",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: !that.$refs?.form?.getFieldsValue().parkId,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                          that.$refs?.form?.setFieldValue("floor", "");
                          that.$refs?.form?.setFieldValue(
                            "architectureRoomIds",
                            ""
                          );
                          that.getFloor(value);
                        },
                      },
                    },
                    [
                      that.buildingOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floor: {
              typeName: "el-select",
              label: "楼层",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().floor;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled:
                          !that.$refs?.form?.getFieldsValue().buildingId,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("floor", value);
                          that.$refs?.form?.setFieldValue(
                            "architectureRoomIds",
                            ""
                          );
                          that.getRoomList(value);
                        },
                      },
                    },
                    [
                      that.floorOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            architectureRoomIds: {
              typeName: "el-select",
              label: "房间",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().architectureRoomIds;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        multiple: true,
                        disabled: !that.$refs?.form?.getFieldsValue().floor,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "architectureRoomIds",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.roomOptions.map((item) => {
                        let { id } = item;
                        return h("el-option", {
                          props: {
                            label:
                              item.remarks +
                              item.roomStartNum +
                              "——" +
                              item.roomEndNum,
                            value: id + "",
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },

            code: {
              typeName: "el-input",
              label: "能耗终端编号",
            },
            name: {
              typeName: "el-input",
              label: "终端名称",
            },
            sysDeptId: {
              typeName: "el-select",
              label: "所属用能单位",
              render: (h) => {
                return (
                  <div>
                    <CascaderSelect
                      values={this.$refs?.form?.getFieldsValue().sysDeptId}
                      value={this.$refs?.form?.getFieldsValue().sysDeptId}
                      varient={"energy"}
                      size={"small"}
                      onInput={(value) => this.setVal(value, "sysDeptId")}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            location: {
              typeName: "el-input",
              label: "终端地址",
            },
            latitude: {
              typeName: "el-select",
              label: "终端经度",
              render: (h) => {
                return (
                  <div class="map">
                    <el-input
                      value={this.$refs?.form?.getFieldsValue().latitude}
                      placeholder="请输入或选择能耗终端经度"
                      maxlength={14}
                      clearable
                      onInput={(value) => this.setVal(value, "latitude")}
                    ></el-input>
                    <el-button onClick={this.openMap}>地图</el-button>
                  </div>
                );
              },
            },
            longitude: {
              typeName: "el-select",
              label: "终端纬度",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      value={this.$refs?.form?.getFieldsValue().longitude}
                      placeholder="请输入或选择能耗终端纬度"
                      maxlength={14}
                      clearable
                      onInput={(value) => this.setVal(value, "longitude")}
                    ></el-input>
                  </div>
                );
              },
            },
            area: {
              label: "用能面积",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入用能面积"
                      value={this.$refs?.form?.getFieldsValue().area}
                      clearable
                      onInput={(value) => this.setVal(value, "area")}
                    >
                      <template slot="append">平方</template>
                    </el-input>
                  </div>
                );
              },
            },
            energySubarea: {
              label: "分区类别",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_subarea_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().energySubarea;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择分区类别",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "energySubarea",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            energySubareaChild: {
              label: "分区子类",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_subarea_child_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().energySubareaChild;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择分区子类",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "energySubareaChild",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            specialEnergyFlag: {
              label: "场所职能",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.site_functions.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().specialEnergyFlag;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择场所职能",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "specialEnergyFlag",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            orientation: {
              label: "朝向",
              bsColumn: {
                col: 1,
              },
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.orientation.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().orientation;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择朝向",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("orientation", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            maleNum: {
              label: "男性人数",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={this.$refs?.form?.getFieldsValue().maleNum}
                      min={0}
                      onInput={(value) => this.setVal(value, "maleNum")}
                    ></el-input-number>
                  </div>
                );
              },
            },
            maleAgeRangeStart: {
              label: "年龄范围开始",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={
                        this.$refs?.form?.getFieldsValue().maleAgeRangeStart
                      }
                      min={0}
                      max={
                        this.$refs?.form?.getFieldsValue().maleAgeRangeEnd ||
                        150
                      }
                      onInput={(value) =>
                        this.setVal(value, "maleAgeRangeStart")
                      }
                    ></el-input-number>
                  </div>
                );
              },
            },
            maleAgeRangeEnd: {
              label: "年龄范围结束",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={this.$refs?.form?.getFieldsValue().maleAgeRangeEnd}
                      min={this.$refs?.form?.getFieldsValue().maleAgeRangeStart}
                      max={150}
                      onInput={(value) => this.setVal(value, "maleAgeRangeEnd")}
                    ></el-input-number>
                  </div>
                );
              },
            },
            femaleNum: {
              label: "女性人数",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={this.$refs?.form?.getFieldsValue().femaleNum}
                      min={0}
                      onInput={(value) => this.setVal(value, "femaleNum")}
                    ></el-input-number>
                  </div>
                );
              },
            },
            femaleAgeRangeStart: {
              label: "年龄范围开始",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={
                        this.$refs?.form?.getFieldsValue().femaleAgeRangeStart
                      }
                      min={0}
                      max={
                        this.$refs?.form?.getFieldsValue().femaleAgeRangeEnd ||
                        150
                      }
                      onInput={(value) =>
                        this.setVal(value, "femaleAgeRangeStart")
                      }
                    ></el-input-number>
                  </div>
                );
              },
            },
            femaleAgeRangeEnd: {
              label: "年龄范围结束",
              bsColumn: {
                col: 3,
              },
              render: (h) => {
                return (
                  <div>
                    <el-input-number
                      value={
                        this.$refs?.form?.getFieldsValue().femaleAgeRangeEnd
                      }
                      min={
                        this.$refs?.form?.getFieldsValue().femaleAgeRangeStart
                      }
                      max={150}
                      onInput={(value) =>
                        this.setVal(value, "femaleAgeRangeEnd")
                      }
                    ></el-input-number>
                  </div>
                );
              },
            },
            userNum: {
              label: "用能人数",
              render: (h) => {
                return (
                  <div>
                    {/* <el-input-number

                      placeholder="请输入用能人数"
                      value={this.$refs?.form?.getFieldsValue().userNum}
                      min={0}
                      onInput={(value) => this.setVal(value, "userNum")}
                    ></el-input-number> */}
                    {this.$refs?.form?.getFieldsValue().userNum || 0} 人
                  </div>
                );
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.getPark();
        if (String(this.id).length > 0) {
          this.getInfo();
        } else {
          this.getCode();
        }
      }
    },
  },
  methods: {
    getCode() {
      maxCode().then((res) => {
        if (res.code === 700) {
          this.$message.warning(res.msg);
          return false;
        }
        this.$refs?.form?.setFieldValue("code", res.data);
      });
    },
    getInfo() {
      detail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.area = dealElectricity(res?.data?.area);
          newData.floor = res?.data?.architectureInfoVo?.facilitiesId;
          newData.buildingId = res?.data?.architectureInfoVo?.buildingId;
          newData.parkId = res?.data?.architectureInfoVo?.parkId;
          this.getBuilding(newData.parkId);
          this.getFloor(newData.buildingId);
          this.getRoomList(newData.floor);
          newData.architectureRoomIds =
            res?.data?.architectureRoomIds.split(",");
          this.$refs?.form?.setFieldsValue(newData);
          this.latlng = {
            lat: newData.latitude,
            lng: newData.longitude,
          };
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!300011");
        });
    },
    getPark() {
      getParkList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.parkOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300406");
        });
    },
    getBuilding(val) {
      if (!val) return false;
      getBuildingList({ parkId: val })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.buildingOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300407");
        });
    },
    getFloor(val) {
      if (!val) return false;
      getFloorList({ buildingId: val })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.floorOptions = res.rows;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300412");
        });
    },
    getRoomList(val) {
      if (!val) return false;
      getArchitectureRoomList({ facilitiesId: val })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.roomOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300408");
        });
    },
    getLatlng(e) {
      const { lat, lng } = e;
      this.$refs?.form?.setFieldValue("latitude", lat.toFixed(7));
      this.$refs?.form?.setFieldValue("longitude", lng.toFixed(7));
      this.latlng = {
        lat,
        lng,
      };
    },

    // 选择地图
    openMap() {
      this.mapShow = true;
    },
    close(status) {
      this.mapShow = false;
    },
    setVal(value, key) {
      if (key === "femaleNum" || key === "maleNum") {
        let a = this.$refs?.form?.getFieldsValue().maleNum || 0;
        let b = this.$refs?.form?.getFieldsValue().femaleNum || 0;
        this.$refs?.form?.setFieldValue("userNum", a + b);
      }
      if (key === "sysDeptId") {
        let result;
        if (value && value.length > 0) {
          result = value[value.length - 1];
        } else {
          result = null;
        }
        this.$refs?.form?.setFieldValue("sysDeptId", result);
      } else if (key === "area") {
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 2));
      } else {
        this.$refs?.form?.setFieldValue(key, value);
      }
    },

    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            ...this.$refs.form.getFieldsValue(),
            area: this.$refs.form.getFieldsValue().area * 100,
            facilitiesId: this.$refs.form.getFieldsValue().floor,
            architectureRoomIds: this.$refs.form
              .getFieldsValue()
              .architectureRoomIds.join(","),
          };
          this.loading = true;
          if (this.id) {
            edit(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!30013");
              });
          } else {
            add(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!30012");
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
  .flex {
    display: flex;
    .margin10 {
      margin: 0 10px;
    }
  }
}
</style>
